package net.stogi.dsper.ui.server.module.datasource;

import net.stogi.common.gwt.dispatch.server.core.ActionHandler;
import net.stogi.common.gwt.dispatch.shared.exception.ActionException;
import net.stogi.common.security.service.SecurityService;
import net.stogi.dsper.api.service.DataSourceService;
import net.stogi.dsper.api.service.UserService;
import net.stogi.dsper.ui.shared.module.datasource.SaveDataSourceAction;
import net.stogi.dsper.ui.shared.module.datasource.SaveDataSourceResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("DsperUi.Dispatch.SaveDataSourceActionHandler")
public class SaveDataSourceActionHandler implements ActionHandler<SaveDataSourceAction, SaveDataSourceResult> {

	private static final Logger log = LoggerFactory.getLogger(SaveDataSourceActionHandler.class);

	@Autowired
	private SecurityService securityService;

	@Autowired
	private DataSourceService dataSourceService;

	@Autowired
	private UserService userService;

	@Override
	public SaveDataSourceResult execute(SaveDataSourceAction action) throws ActionException {
		log.trace("execute(): invoke [ action = '{}']", action);

		SaveDataSourceResult result;

		try {
			Long userId = userService.getUserByUsername(securityService.getLoggedUserPrincipalData().getUsername()).getId();

			result = new SaveDataSourceResult(dataSourceService.saveDataSource(userId, action.getDataSource()));
		}
		catch (Exception e) {
			throw new ActionException(e);
		}

		return result;
	}

	@Override
	public Class<SaveDataSourceAction> getActionType() {
		return SaveDataSourceAction.class;
	}

	@Override
	public void rollback(SaveDataSourceAction action, SaveDataSourceResult result) throws ActionException {}
}
